package com.gitee.wsl.struct.generator.segment

import kotlinx.atomicfu.AtomicLong
import kotlinx.atomicfu.atomic
import kotlin.concurrent.Volatile

/**
 * 特别声明: 此算法来自美团的leaf号段模式
 * see： https://github.com/Meituan-Dianping/Leaf/blob/master/leaf-server/src/main/java/com/sankuai/inf/leaf/server/service/SegmentService.java
 */
class Segment(val buffer: SegmentBuffer) {
    var value: AtomicLong = atomic(0L)

    @Volatile
    var max: Long = 0

    @Volatile
    var step: Int = 0

    val idle: Long
        get() = this.max - value.value

    override fun toString(): String {
        val sb = StringBuilder("Segment(")
        sb.append("value:")
        sb.append(value)
        sb.append(",max:")
        sb.append(max)
        sb.append(",step:")
        sb.append(step)
        sb.append(")")
        return sb.toString()
    }
}
